package com.zly.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zly.service.entity.Permission;
import com.zly.service.entity.Role;
import com.zly.service.entity.SecurityUserDetails;
import com.zly.service.entity.User;
import com.zly.service.mapper.PermissionMapper;
import com.zly.service.mapper.RoleMapper;
import com.zly.service.mapper.UserMapper;
import com.zly.service.service.UserDetailsServiceManager;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceManagerImpl implements UserDetailsServiceManager {
    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private PermissionMapper permissionMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        if (user==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        List<Role> roleList = roleMapper.selectList(new LambdaQueryWrapper<Role>().eq(Role::getUserId, user.getId()));
        List<Permission> permissionList = permissionMapper.selectList(new LambdaQueryWrapper<Permission>().in(Permission::getRoleId, roleList.stream().map(Role::getId).toList()));
        List<String> roles = roleList.stream().map(Role::getRole).toList();
        List<String> permissions = permissionList.stream().map(Permission::getPermission).toList();
        ArrayList<String> authorities = new ArrayList<>();
        authorities.addAll(roles);
        authorities.addAll(permissions);
        user.setPermissionList(authorities);
        return new SecurityUserDetails(user);
    }

    @Override
    public void createUser(UserDetails user) {

    }

    @Override
    public void updateUser(UserDetails user) {

    }

    @Override
    public void deleteUser(String username) {

    }

    @Override
    public void changePassword(String oldPassword, String newPassword) {

    }

    @Override
    public boolean userExists(String username) {
        return false;
    }
}
